package com.binance.assetservice.web.service.impl;

import org.javasimon.aop.Monitored;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.binance.assetservice.web.service.IOrderBookService;

public class OrderBookServiceImpl implements IOrderBookService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final RestTemplate template;

    /**
     * kline sample data [ 1440084300000, //time 30000, //open 30000, //high 30000, //low 30000,
     * //close 0.01 //volume ]
     */

    private final String symbol;
    private final String restUrl;
    private volatile JSONArray todayTrades = new JSONArray();
    private double volume = 0;
    private double turnover = 0;
    private Double open = 0D;
    private Double close = 0D;
    private Double low = 0D;
    private Double high = 0D;
    private volatile JSONObject ticker = null;
    private volatile Long lastAggTradeId = -1L;
    private double activeBuy = 0;

    public OrderBookServiceImpl(String symbol, RestTemplate template, String restUrl) {
        this.symbol = symbol;
        this.template = template;
        this.restUrl = restUrl;
        init();
    }

    public void init() {
        initStats();
    }

    @Monitored
    @Override
    public void initStats() {
        try {
            UriComponentsBuilder builder1 = UriComponentsBuilder.fromHttpUrl(String.format("%s/ticker/price", restUrl))
                    .queryParam("symbol", symbol);
            String priceResult = template.getForObject(builder1.build().toUriString(), String.class, symbol);
            JSONObject priceObj = JSONObject.parseObject(priceResult);
            if (priceObj != null) {
                if (priceObj.containsKey("price")) {
                    close = priceObj.getDouble("price"); // close
                } else {
                    close = new Double(0);
                }
            } else {
                close = new Double(0); // close
            }

            UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(String.format("%s/ticker/24hr", restUrl))
                    .queryParam("symbol", symbol);
            String result = template.getForObject(builder.build().toUriString(), String.class, symbol);
            JSONObject obj = JSONObject.parseObject(result);
            if (obj != null) {
                if (obj.containsKey("openPrice")) {
                    open = obj.getDouble("openPrice");// open
                } else {
                    open = new Double(0);
                }
                if (obj.containsKey("highPrice")) {
                    high = obj.getDouble("highPrice"); // high
                } else {
                    high = new Double(0); // high
                }
                if (obj.containsKey("lowPrice")) {
                    low = obj.getDouble("lowPrice"); // low
                } else {
                    low = new Double(0); // low
                }
                if (obj.containsKey("volume")) {
                    volume = obj.getDouble("volume"); // volume
                } else {
                    volume = 0;
                }
                if (obj.containsKey("quoteVolume")) {
                    turnover = obj.getDouble("quoteVolume"); // quote volume
                } else {
                    turnover = 0;
                }
            } else {
                volume = 0;
                turnover = 0;
                open = new Double(0); // open
                high = new Double(0); // high
                low = new Double(0); // low
            }
        } catch (HttpStatusCodeException e) {
            logger.error("产品:{} 行情初始化失败:{}", symbol, e.getResponseBodyAsString());
        } catch (Exception e) {
            logger.error("产品:{} 行情初始化失败:{}", symbol, e);
        }

    }

    @Override
    public Long getLastAggTradeId() {
        return lastAggTradeId;
    }

    @Override
    public double getActiveBuy() {
        return activeBuy;
    }

    @Override
    public double getActiveSell() {
        return volume - activeBuy;
    }

    @Override
    public JSONArray getTodayTrades() {
        return todayTrades;
    }

    @Override
    public JSONObject getTicker() {
        return ticker;
    }

    @Override
    public void setTicker(JSONObject ticker) {
        this.ticker = ticker;
    }

    @Override
    public Double getVolume() {
        return volume;
    }

    @Override
    public Double getTurnOver() {
        return turnover;
    }

    @Override
    public Double getOpen() {
        return open;
    }

    @Override
    public Double getLow() {
        return low;
    }

    @Override
    public Double getHigh() {
        return high;
    }

    @Override
    public Double getClose() {
        return close;
    }

    @Override
    public void setKlineT(JSONObject klineT) {
        if (klineT != null) {
            open = klineT.getDouble("o");// open
            high = klineT.getDouble("h"); // high
            low = klineT.getDouble("l"); // low
            close = klineT.getDouble("c"); // close
            volume = klineT.getDouble("v"); // volume
            turnover = klineT.getDouble("q"); // quote volume
        }
    }

}
